<template>
	<view>
		<!-- 顶部导航栏 -->
		<cu-custom bgColor="bg-gradual-green" :isBack="true">
			<block slot="content">课程详情</block>
		</cu-custom>

		<!-- 消息提示 -->
		<message ref="message"></message>

		<scroll-view scroll-y :style="{'height': 'calc(100vh - ' + scheight +'rpx);'}">
			<!-- 轮播图 -->
			<swiper class="screen-swiper margin round-dot" :indicator-dots="true" :circular="true" :autoplay="true"
				interval="5000" duration="500" style="height: 160px;">
				<swiper-item v-for="(item,index) in course.rotationList" :key="index">
					<image :src="setting.fileUrl + '/' + item.url + '/' + item.code" mode="aspectFill"></image>
				</swiper-item>
			</swiper>

			<!-- 课程信息 -->
			<view class="cu-card bg-white padding margin radius">
				<!-- 课程价格 -->
				<view class="flex justify-between">
					<view class="text-price text-xxl text-red text-bold">{{course.price}}</view>
					<view class="text-df text-gray">限售：{{ course.surplus }}/{{course.capacity}}</view>
				</view>
				<!-- 课程名 -->
				<view class="text-xxl text-bold text-black margin-top margin-bottom">
					{{ course.name }}
				</view>
				<!-- 开课时间 课时 -->
				<view class="flex align-center text-black margin-bottom">
					<view>{{ parseTime(course.startTime, '{y}.{m}.{d}') }}</view>
					<view>-</view>
					<view>{{ parseTime(course.finishTime, '{m}.{d}') }}</view>
					<view class="margin-left margin-right">|</view>
					<view>{{course.lessonDuration}}课时</view>
				</view>
				<view class="text-black margin-bottom">
					线下体验时间：{{parseTime(course.experienceTime, '{y}.{m}.{d},{m}:{d}')}}
				</view>
				<!-- 标签 -->
				<view class="flex">
					<view class='cu-tag bg-orange round'>{{course.classify}}</view>
					<view class='cu-tag bg-olive round'>{{course.age}}</view>
				</view>
			</view>

			<!-- 课程介绍 -->
			<view>
				<rich-text class="cu-card bg-white margin padding remark" :nodes="course.remark | formatRichText">
				</rich-text>
				<!-- <view class="cu-card bg-white margin padding remark" v-html="course.remark"></view> -->
				<view class="cu-card bg-white margin padding">
					<view class="cu-card bg-grey margin-top" v-for="item in course.classTime" :key="item.id">
						{{item.title}},{{parseTime(item.startTime, '{h}:{i}') + '-' + parseTime(item.endTime, '{h}:{i}')}},地点：
						{{item.place}}
					</view>
				</view>
				<view class="cu-card bg-white margin padding">
					<view v-for="item in course.teacherList" :key="item.id">
						教师：{{item.realName}}, 简介： {{item.introduction}}
					</view>
				</view>
				<view class="cu-card bg-white margin">
					评价
					{{JSON.stringify(evaluateList)}}
				</view>
			</view>
		</scroll-view>


		<!-- 底部购买操作 -->
		<view class="cu-bar bg-white tabbar border foot" v-show="!checkBuy">
			<button class="action basis-xs" open-type="contact">
				<view class="cuIcon-service text-green">
				</view> 客服
			</button>
			<view class="flex basis-xl text-center margin-left margin-right">
				<button class="cu-btn bg-olive round shadow-blur margin-right" style="width: 50%;"
					@click="handleReserve">{{checkReserve?'取消预约':'预约体验'}}</button>
				<button class="cu-btn bg-red round shadow-blur margin-right" style="width: 50%;"
					@click="buyCourse">立即购买</button>
			</view>
		</view>

		<!-- 加载弹窗 -->
		<view class="cu-load load-modal" v-if="loadModal">
			<image src="@/static/logo.jpg" mode="aspectFit"></image>
			<view class="gray-text">加载中...</view>
		</view>
	</view>
</template>

<script>
	import {
		getCourseById,
		checkBuyCourse
	} from '@/api/course.js'

	import {
		checkReserveByCourseId,
		reserveByCourseId,
		cancleReserveByCourseId
	} from '@/api/reserve.js'

	import {
		getEvaluateByCourseId
	} from '@/api/evaluate.js'

	import setting from '@/settings.js'
	import {
		parseTime
	} from '@/utils/parse.js'

	export default {
		data() {
			return {
				id: undefined,
				course: {},
				evaluateList: [],
				setting,
				checkBuy: false,
				checkReserve: false,
				// 加载弹窗
				loadModal: true
			}
		},
		created() {
			this.id = this.$store.getters.courseId
			// 检查登录状态。登录获取用户预约及购买信息
			if (uni.getStorageSync('token')) {
				this.checkIsBuy()
				this.checkIsReserve()
			}
			this.getCourseInfo()
			this.getEvaluateList()
		},
		onShow() {
			if (uni.getStorageSync('token')) {
				this.checkIsBuy()
				this.checkIsReserve()
			}
		},
		computed: {
			scheight() {
				return this.checkBuy ? 150 : 250
			}
		},
		methods: {
			parseTime,
			getCourseInfo() {
				getCourseById(this.id).then(res => {
					this.course = res.data
					this.loadModal = false
				})
			},
			getEvaluateList() {
				getEvaluateByCourseId(this.id).then(res => {
					this.evaluateList = res.data
					this.loadModal = false
				})
			},
			// 检查课程是否购买
			checkIsBuy() {
				checkBuyCourse(this.id).then(res => {
					if (res.data > 0) {
						this.checkBuy = true
					}
				})
			},
			// 检查是否预约线下体验课
			checkIsReserve() {
				checkReserveByCourseId(this.id).then(res => {
					if (res.data > 0) {
						this.checkReserve = true
					}
				})
			},
			// 点击预约按钮线下体验课处理函数
			handleReserve() {
				if (uni.getStorageSync('token')) {
					if (this.checkReserve) {
						this.cancleReserve()
					} else {
						// 弹出提示,是否需要发送消息
						const _this = this
						//#ifdef MP-WEIXIN
						wx.requestSubscribeMessage({
							tmplIds: [setting.classMessageId],
							success(res) {
								const s = res[setting.classMessageId]
								if (s === "accept") {
									console.log("用户同意订阅该条id对应的模板消息");
								} else if (s === "reject") {
									console.log("用户拒绝订阅该条id对应的模板消息");
								} else if (s === "ban") {
									console.log("已被后台封禁");
								} else {
									console.log("该模板因为模板标题同名被后台过滤");
								}
							},
							fail(err) {
								console.log("错误");
								console.log(err);
							},
							complete() {
								console.log(111);
								wx.requestSubscribeMessage({
									tmplIds: [setting.classMessageId],
									success(res) {
										const s = res[setting.classMessageId]
										if (s === "accept") {
											console.log("用户同意订阅该条id对应的模板消息");
										} else if (s === "reject") {
											console.log("用户拒绝订阅该条id对应的模板消息");
										} else if (s === "ban") {
											console.log("已被后台封禁");
										} else {
											console.log("该模板因为模板标题同名被后台过滤");
										}
									},
									fail(err) {
										console.log("错误");
										console.log(err);
									},
									complete() {
										console.log(222);
										_this.reserveCourse()
										console.log("调用结束");
									}
								})
							}
						})
						//#endif

						// 除了微信小程序
						//#ifndef MP-WEIXIN
						_this.reserveCourse()
						//#endif
					}
				} else {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}
			},
			// 预约体验线下课
			reserveCourse() {
				reserveByCourseId(this.id).then(res => {
					this.$refs.message.success({
						title: res.msg,
						duration: 2000
					})
					this.checkReserve = true
				}).catch(err => {
					this.$refs.message.error({
						title: err.msg,
						duration: 2000
					})
				})
			},
			// 取消预约线下体验
			cancleReserve() {
				cancleReserveByCourseId(this.id).then(res => {
					this.$refs.message.success({
						title: res.msg,
						duration: 2000
					})
					this.checkReserve = false
				}).catch(err => {
					this.$refs.message.error({
						title: err.msg,
						duration: 2000
					})
				})
			},
			// 购买课程,跳转创建订单页面
			buyCourse() {
				if (uni.getStorageSync('token')) {
					this.$store.commit('course/set_courseId', this.id)
					uni.navigateTo({
						url: '/pages/order/create-order/create-order'
					})
				} else {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}
			}
		},
		filters: {
		            formatRichText(html) { //控制小程序中图片大小
					if(!html) {
						return html
					}
		                let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		                    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		                    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		                    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		                    return match;
		                });
		                newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		                    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
		                    return match;
		                });
		                newContent = newContent.replace(/<br[^>]*\/>/gi, '');
		                newContent = newContent.replace(/\<img/gi,
		                    '<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
		                return newContent;
		            }
		        }
	}
</script>

<style scoped>
	.remark img {
		width: 100%;
	}
</style>
